<?php

namespace App\Http\Controllers\Api;


use App\Services\Wechat\MiniProgramService;
use App\Traits\WeChat\WechatPayManagers;
use Illuminate\Http\Request;

class MiniprogramController extends BaseController
{
    use WechatPayManagers;

    /**
     * 小程序登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        try {
            $code = $request->input('code');
            $appid = $request->input('appid') ?: $request->header('appid');
            $session = $this->miniprogram($appid)->auth->session($code);
            $wechatUserInfo = $request->input('wechatUserInfo');
            $service = new MiniProgramService();
            $user = $service->register($appid, $wechatUserInfo, $session['openid'], $session['unionid'] ?? null);
            return ajaxReturn([
                'openid' => $session['openid'],
                'access_token' => $user->createToken($session['openid'])->accessToken,
                'userinfo' => $user->only(['uid', 'gid', 'username', 'email', 'mobile', 'avatar'])
            ]);
        } catch (\EasyWeChat\Kernel\Exceptions\InvalidConfigException $exception) {
            return ajaxError(500, $exception->getMessage());
        }
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function getOpenid(Request $request)
    {
        $code = $request->input('code');
        $appid = $request->input('appid') ?: $request->header('appid');
        $session = $this->miniprogram($appid)->auth->session($code);
        return ajaxReturn(['openid' => $session['openid']]);
    }
}
